<?php

namespace app\merchant\controller;

use app\common\controller\ActionLogs;
use app\common\controller\Platinfo;
use app\common\controller\Platurl;
use app\common\model\Agent;
use app\common\model\WxOpen;
use app\common\model\ActionLog;
use app\common\model\LoginCode;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\MerchantCashier;
use app\common\model\Momerchant;
use think\Controller;
use think\Request;
use think\Session;
use think\Validate;
use thinkcms\auth\Auth;
use Wechat\Wxobjopen;

class Login extends Controller
{


    public function index()
    {
        return $this->fetch('login');
    }

    public function login()
    {
        $request = request();
        if ($request->isAjax()) {
            if ($request->post('remember') == 1) {
                cookie('username', $request->post('username'), 1209600);
                cookie('password', $request->post('password'), 1209600);
            }
            $sdata = [];
            $data = $request->param();
            $validate = new Validate([
                'username|用户名' => 'require',
                'password|密码' => 'require',
                'code|验证码' => 'require|captcha'
            ]);
            if (!$validate->check($data)) {
                $sdata = array('code' => '8', 'message' => $validate->getError());
            } else {
                $User = new LoginUsers();
                $user = $User->where('username', $data['username'])->find();
                if ($this->check_pass_error($user) == 1) {
                    $sdata = array('code' => 6, 'message' => '您的账号已被锁定，请稍后再试');
                } else {
                    if ($user) {
                        $res_chack_agent = $this->check_agent($user);
                        if ($res_chack_agent['code'] == 1) {
                            if ($user['password'] == MD5($data['password']) && ($user['level'] == "3001" || $user['level'] == "3002" || $user['level'] == "3003" || $user['level'] == "3004")) {

                                $auth = new Auth();
                                $auth->login($user['id'], $user['username']);
                                $auth->createLog('管理员<spen style=\'color: #1dd2af;\'>[ ' . $data["username"] . ' ]</spen>登陆了后台,', '后台登录', 'login');
                                $url = url('Index/index');

                                Session::set('login_mid', $user['mid']);
                                Session::set('level', $user['level']);
                                Session::set('login_top_mid', $user['top_mid']);
                                //所属平台网址
                                $Platurl = new Platurl();
                                $plat_url = $Platurl->getagenturl('top_mid', $user['top_mid']);
                                Session::set('login_plat_url', $plat_url);
                                //END
                                $sdata = array("code" => 0, "message" => "登录成功", 'url' => $url);
                            } else {
                                $User->where('id', $user['id'])->setInc('pass_error');
                                if ($user['pass_error'] == 4) {
                                    $User->save(['lock_time' => time()], ['id' => $user['id']]);
                                }
                                $sdata = array("code" => 1, "message" => "账号或密码错误");
                            }
                        }else{
                            $sdata = array("code" => 1, "message" => "已到期");
                        }
                    } else {
                        $sdata = array("code" => 1, "message" => "账号或密码错误");
                    }
                }
            }
        } else {
            $sdata = array('code' => 9999, 'message' => "非法访问");
        }
        return json($sdata);
    }

    //检查登陆账号代理商是否正常
    private function check_agent($user){
        //所属平台信息
        $Platinfo = new Platinfo();
        if ($user['top_mid']) {
            $plat_info = $Platinfo->getagentinfo('top_mid', $user['top_mid']);
        }elseif($user['mid']){
            $plat_info = $Platinfo->getagentinfo('mid', $user['mid']);
        }else{
            $plat_info['agent_id'] = "";
        }
        //END
        $CardApiBase = new CardApiBase();
        $CardApiBase->getcopyright($plat_info['agent_id']);
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("payos", "login", "check_agent/cop", "1:", $plat_info);
        //此代理商是否被停用
        if ($plat_info['agent_id'] == 24 || $plat_info['agent_id'] == 28 || $plat_info['agent_id'] == 32){
//            $res_data['code'] = 9999;
            $res_data['code'] = 1;
        }else{
            $res_data['code'] = 1;
        }
        return $res_data;
    }

    private function check_pass_error($user)
    {
        if ($user['pass_error'] >= 5) {
            if ($user['lock_time'] + 600 > time()) {
                $sdata = 1;
            } else {
                $User = new LoginUsers();
                $User->save(['pass_error' => 0, 'lock_time' => 0], ['id' => $user['id']]);
                $sdata = 0;
            }
        } else {
            $sdata = 0;
        }
        return $sdata;
    }

//电脑端生成二维码
    public function getqrlogin()
    {
        if (request()->isAjax()) {
            $str_rand = $this->generate_code();
            $LoginCode = new LoginCode();
            $LoginCode->save(['code' => $str_rand, 'addtime' => time(), 'action' => 'login']);
            $login_url = "https://" . $_SERVER['HTTP_HOST'] . url('login/checkcodelogin', ['scode' => $str_rand]);
            $xml = '<?xml version="1.0" encoding="utf-8"?>
                    <request>
                    <type>codelogin</type>
                    <code>' . $str_rand . '</code>
                    </request>
                ';
            $data = array('code' => $str_rand, 'shuju' => $xml, 'login_url' => $login_url);
            return json($data);
        }
    }

    //手机端确认登陆
    public function checkcodelogin()
    {

        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $System = new \app\common\model\System();
        $config2 = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where(array('id' => $config2['wx_open_id']))->find();
        $options = array(
            'component_token' => $config2['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config2['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config2['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config2['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config2['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
//        file_put_contents('/data2/html/payos/test.txt', 'login-9' . json_encode($options,JSON_UNESCAPED_UNICODE), FILE_APPEND);
        Session::clear('openid');
        $openid = session('openid');
//        file_put_contents('/data2/html/payos/test.txt', 'login-9' . json_encode($openid,JSON_UNESCAPED_UNICODE), FILE_APPEND);
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
//            file_put_contents('/data2/html/payos/test.txt', 'login-7' . json_encode($info,JSON_UNESCAPED_UNICODE), FILE_APPEND);
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Login/checkcodelogin", array('scode' => request()->param('scode')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');
                header("Location: $url");
                exit();
            } else {
                $openid = $info['openid'];
            }
        }
        $LoginUsers = new LoginUsers();
        $loginuser = $LoginUsers->where(['openid' => $openid])->find();
//        var_dump($openid);
        if ($loginuser['mid'] !== 0 && ($loginuser['level'] == 3002 || $loginuser['level'] == 3003)) {
            Session::set('code', request()->param('scode'));
            $map['id'] = array('in', $loginuser['mid']);
            $Merchant = new Merchant();
            $mach = $Merchant->where($map)->select();
//            var_dump($Merchant->getLastSql());
            $path = "";
        } elseif ($loginuser['top_mid'] !== 0 && $loginuser['level'] == 3001) {
            Session::set('code', request()->param('scode'));
            $map['id'] = array('in', $loginuser['top_mid']);
            $Merchant = new Momerchant();
            $mach = $Merchant->where($map)->select();
//            var_dump($Merchant->getLastSql());
            $path = "login/checkcodelogin2";
        } else {
//            var_dump($LoginUsers->getLastSql());
            $mach = [];
            $path = "";
        }

        $LoginCode = new LoginCode();
        $status = $LoginCode->where(['action' => 'login', 'code' => request()->param('scode')])->value('status');
        if ($status == 2 || $status == 3) {
            $this->error('该授权码已被使用,请重试');
        } elseif ($status == 4) {
            $this->error('该授权码过期');
        } else {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $jssdk = $weObj->getJsSign($url);
            $this->assign('jssdk', $jssdk);
            $LoginCode->save(['status' => 1, 'openid' => $openid, 'level' => $loginuser['level']], ['action' => 'login', 'code' => request()->param('scode')]);
            $this->assign('mach', $mach);
            return $this->fetch($path);
        }
    }

//手机确认授权登陆页面
    public function querycodelogin()
    {
        $code = Session::get('code');
        if (request()->isAjax()) {
            $LoginCode = new LoginCode();
            $status = $LoginCode->where(['action' => 'login', 'code' => $code])->value('status');
            if ($status == 2 && $status == 3) {
                $message = array('code' => 9002, 'message' => '该授权码已被使用,请重试');
            } elseif ($status == 4) {
                $message = array('code' => 9004, 'message' => '该授权码过期');
            } else {
                $mid = Session::get('login_mid');
                $top_mid = Session::get('login_top_mid');
                $datas['status'] = 2;
                if (isset($mid)) {
                    $datas['mid'] = intval($mid);
                } elseif (isset($top_mid)) {
                    $datas['mid'] = intval($top_mid);
                }
                $map['code'] = $code;
                $map['action'] = 'login';
                $LoginCode = new LoginCode();
                $cos = $LoginCode->save($datas, $map);
                if ($cos) {
                    $message = array('code' => 0, 'message' => '授权成功');
                } else {
                    $message = array('code' => 9999, 'message' => '授权失败');
                }
            }
            return json($message);
        } else {
            $LoginCode = new LoginCode();
            $status = $LoginCode->where(['action' => 'login', 'code' => $code])->value('status');
            if ($status == 3) {
                $this->error('该授权码已被使用,请重试');
            } elseif ($status == 4) {
                $this->error('该授权码过期');
            } else {
                $map['code'] = $code;
                $map['action'] = 'login';
                $LoginCode = new LoginCode();
                $cos = $LoginCode->where($map)->find();
                if ($cos) {
                    $mid = request()->param('mid');
                    $top_mid = request()->param('top_mid');
                    if (isset($mid)) {
                        Session::set('login_mid', $mid);
                        $Merchant = new Merchant();
                        $merchant = $Merchant->where(['id'=>$mid])->field('merchant,img')->find();
                    } elseif (isset($top_mid)) {
                        Session::set('login_top_mid', $top_mid);
                        $Momerchant = new Momerchant();
                        $merchant = $Momerchant->where(['id'=>$top_mid])->field('merchant_name,img')->find();
                    }
//                    file_put_contents('/data2/html/payos/test.txt', 'login-2-' . json_encode($merchant), FILE_APPEND);
                    $this->assign('codes', $cos);
                    $this->assign('merchant', $merchant);
                    return $this->fetch();
                } else {
                    $this->error('非法访问');
                }
            }
        }
    }

//生成50位随机code
    private function generate_code($length = 50)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-';
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $code;
    }

    //扫码自动登陆方法
    public function qrcodelogin()
    {
        $code = request()->param('code');
        $Logincode = new LoginCode();
        $lcode = $Logincode->where(['code' => $code])->find();
        if ($lcode['status'] == 2) {
            if ($lcode['level'] == 3001) {
                Session::set('login_top_mid', $lcode['mid']);
            } elseif ($lcode['level'] == 3002 || $lcode['level'] == 3003) {
                Session::set('login_mid', $lcode['mid']);
            }
            Session::set('login_user_qx', $lcode['level']);
            $LoginUser = LoginUsers::get(['openid' => $lcode['openid']]);
            if ($LoginUser) {
                $Logincode->save(['status' => 3], ['code' => $code]);
                $auth = new Auth();
                $auth->login($LoginUser['id'], $LoginUser['username']);
                $auth->createLog('管理员<spen style=\'color: #1dd2af;\'>[ ' . $LoginUser["username"] . ' ]</spen>登陆了后台,', '后台登录', 'login');
                $url = url('Index/index');
                Session::set('mid', $LoginUser['mid']);
                Session::set('level', $LoginUser['level']);
                $this->redirect($url);
            }
        } else {
            $this->error('非法访问');
        }
    }

    public function authbangding()
    {
//        $Agent = new Agent();
//        $WxOpen = new WxOpen();
//        $System = new \app\common\model\System();
//        $config2 = $System->where(array('id' => 1))->find();
//        $users = $WxOpen->where(array('id' => $config2['wx_open_id']))->find();
//        $options = array(
//            'component_token' => $config2['component_token'], // 填写你设定的key
//            'component_encodingaeskey' => $config2['component_encodingaeskey'], // 填写加密用的EncodingAESKey
//            'component_appid' => $config2['component_appid'], // 填写高级调用功能的app id
//            'component_appsecret' => $config2['component_appsecret'], // 填写高级调用功能的密钥
//            'open_ticket' => $config2['open_ticket'],
//            'authorizer_appid' => $users['authorizer_appid'],
//            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
//        );
        $Merchant = new Merchant();
        $mid = $Merchant->where(['top_mid'=>request()->param('top_mid')])->value('id');
        $Platurl = new Platurl();
        $options = $Platurl->getagenttplmsg($mid);
            $weObj = new Wxobjopen($options);
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {

                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Login/authbangding", array('scode' => request()->param('scode'), 'id' => request()->param('id'),'top_mid'=>request()->param('top_mid')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');
                header("Location: $url");
                exit();
            } else {
                $openid = $info['openid'];
                $openuserinfo=$weObj->getUserInfo($openid);
                if($openuserinfo['subscribe']==0){
                    $maes['authorizer_appid']=$options['authorizer_appid'];
                    $wxinfo=WxOpen::where($maes)->field('qrcode_url')->find();

$this->assign('wxinfo',$wxinfo);
                   return $this->fetch('guanzhu');
                }
            }
        $LoginCode = new LoginCode();
        $status = $LoginCode->where(['action' => 'bangding', 'code' => request()->param('scode')])->value('status');
        if ($status == 2 || $status == 3) {
            $this->error('该授权码已被使用,请重试');
        } elseif ($status == 4) {
            $this->error('该授权码过期');
        } else {
            $uid = request()->param('id');
            $LoginUser = new LoginUsers();
            $userinfo = $LoginUser->where(['id' => $uid])->find();
            $LoginCode->save(['status' => 1, 'openid' => $openid,'uid'=>$uid,'userinfo'=>json_encode($openuserinfo)], ['action' => 'bangding', 'code' => request()->param('scode')]);
            if ($userinfo['mid'] !== 0) {
                $Mach = new Merchant();
                $map2['id'] = array('in', $userinfo['mid']);
                $machs = $Mach->where($map2)->field('merchant')->select();
                foreach ($machs as $k => $v) {
                    $mach2[] = $v['merchant'];
                }
                $mach = implode(',', $mach2);
            } elseif ($userinfo['top_mid'] !== 0) {
                $Mach = new Momerchant();
                $map2['id'] = array('in', $userinfo['top_mid']);
                $machs = $Mach->where($map2)->field('merchant_name')->select();
                foreach ($machs as $k => $v) {
                    $mach2[] = $v['merchant_name'];
                }
                $mach = implode(',', $machs['merchant_name']);
            }
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $jssdk = $weObj->getJsSign($url);
            $this->assign('jssdk', $jssdk);
            Session::set('bangding_code', request()->param('scode'));
            $this->assign('sy_userinfo', $userinfo);
            $this->assign('mach', $mach);
            return $this->fetch();
        }
    }

    public function query_code_bangding()
    {
        if (request()->isAjax()) {
            $code = Session::get('bangding_code');
            $map['code'] = $code;
            $LoginCode = new LoginCode();
            $status = $LoginCode->where($map)->value('status');
            if ($status == 1) {
                $qs = $LoginCode->save(['status' => 2], $map);
                if ($qs) {
                    $data = array('code' => 0, 'message' => '授权成功');
                } else {
                    $data = array('code' => 9999, 'message' => '授权失败');
                }
            } elseif ($status == 4) {
                $data = array('code' => 9004, 'message' => '授权码已过期');
            } elseif ($status == 3) {
                $data = array('code' => 9004, 'message' => '该授权码已被使用');
            } else {
                $data = array('code' => 9999, 'message' => '授权失败');
            }
            return json($data);
        }
    }

    public function logout()
    {
        Session::clear();
        $auth = new Auth();
        $auth->logout();
        $this->success('退出成功', 'Login/index');
    }
}
